package org.androidpush.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.androidpush.R;
import org.androidpush.client.Constants;
import org.androidpush.utils.ConstantUtils;

import java.io.IOException;

/**
 * Created by huang on 2017/3/31 0031.
 */
public class NotificationActivity extends Activity {

    private static final int MSG_SUCCESS = 0;
    private static final int MSG_FAILURE = 1;

    private EditText txTitle = null, txMessage = null, txUsername;
    private RadioGroup broadcastRadio = null;
    private RadioButton all = null, one = null;
    private Button submit = null;
    private TextView tvUsername = null;
    private String broadcast = "0";
    private String username = null,fromId;
    private boolean status = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xml_notification);
        init();
    }

    private void init() {
        txTitle = (EditText) findViewById(R.id.Id_Title_Et);
        txMessage = (EditText)findViewById(R.id.Id_Message_Ed);
        broadcastRadio = (RadioGroup) findViewById(R.id.Id_Broadcast_Rg);
        all = (RadioButton) findViewById(R.id.Id_All_Rb);
        one = (RadioButton)findViewById(R.id.Id_One_Rb);
        submit = (Button) findViewById(R.id.Id_Submit_B);
        txUsername = (EditText) findViewById(R.id.Id_Username_Et);
        tvUsername = (TextView) findViewById(R.id.Id_Username_Tv);
        SharedPreferences sp = NotificationActivity.this.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_APPEND);
        fromId = sp.getString(ConstantUtils.USER_ID, "");
    }

    private void setListener() {
        broadcastRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == all.getId()) {
                    broadcast = "0";
                    tvUsername.setVisibility(TextView.GONE);
                    txUsername.setVisibility(EditText.GONE);
                    status = true;
                } else if (checkedId == one.getId()) {
                    broadcast = "1";
                    tvUsername.setVisibility(TextView.VISIBLE);
                    txUsername.setVisibility(EditText.VISIBLE);
                    status = false;
                }
            }


        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = ConstantUtils.URL + "xml_notification.do";
                String title = txTitle.getText().toString();
                String message = txMessage.getText().toString();
                if (status) {
                    notificate(url, title, message,fromId);
                } else {
                    username = txUsername.getText().toString();
                    notificate(url, title, message,fromId);
                }
            }
        });
    }

    private void notificate(final String url, final String title, final String message,final String fromId) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                OkHttpClient okHttpClient = new OkHttpClient();
                FormEncodingBuilder builder = new FormEncodingBuilder();
                builder.add("title", title)
                        .add("message", message)
                        .add("broadcast", broadcast)
                        .add("from",fromId);
                if (username != null && "".equals(username)) {
                    builder.add("username", username);
                }

                Request request = new Request.Builder().post(builder.build()).url(url).build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        mhandler.obtainMessage(MSG_FAILURE).sendToTarget();
                        e.printStackTrace();
                        return;
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        String result = (String) response.body().string();
                        Log.d("onResponse", result);
                        if ("SUCCESS".equals(result)) {
                            mhandler.obtainMessage(MSG_SUCCESS).sendToTarget();
                            return;
                        } else {
                            mhandler.obtainMessage(MSG_FAILURE).sendToTarget();
                            return;
                        }
                    }
                });
            }
        }).start();
    }

    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SUCCESS: {
                    ConstantUtils.logToast(NotificationActivity.this, getResources().getString(R.string.str_notification_success));
                    break;
                }
                case MSG_FAILURE: {
                    ConstantUtils.logToast(NotificationActivity.this, getResources().getString(R.string.str_notification_faile));
                    break;
                }
            }
        }
    };
}
